package com.abbcc.module.admin;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import com.abbcc.action.BaseAction;
import com.abbcc.common.CommonConst;
import com.abbcc.helper.JavaMailHelper;
import com.abbcc.models.TdClient;
import com.abbcc.models.TdEmailAccount;
import com.abbcc.service.ClientService;
import com.abbcc.util.ObjectUtil;
import com.abbcc.util.StringUtil;

public class ClientAction extends BaseAction<TdClient>{
	@Autowired
	private ClientService clientService;
	public String searchKey;
	public String emails;
	public int[] clientIds;
	public String title;
	public String content;
	public String save(){
		/*if(getCurrentUser()!=null && getCurrentUser().getToWrite()!=null && (getCurrentUser().getToWrite().equals("0")||getCurrentUser().getToWrite()==null)){
			result = "对不起，您没有添加的权限，请联系管理员开通添加权限!";
			return list();
		}*/
		entity.setAddTime(new Date());
		entity.setState("1");
		clientService.save(entity);
		result = "添加成功!";
		if(getCurrentAdmin()!=null)
			saveLog("客户", result, CommonConst.LOGSAVE, CommonConst.LOGTYPEBYADMIN);
		else
			saveLog("客户", result, CommonConst.LOGSAVE, CommonConst.LOGTYPEBYUSER);
		return list();
	}
	public String addPage(){
		return ADD;
	}
	public String list(){
		DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
		dc.addOrder(Order.desc("addTime"));
		if(StringUtil.isNotBlank(searchKey))
			dc.add(Restrictions.like("name", searchKey,MatchMode.ANYWHERE));
		dc.add(Restrictions.ne("state", "3"));
		pageList = clientService.findPageByCriteria(dc, pageSize, startIndex);
		if(getCurrentAdmin()!=null)
			saveLog("客户", "查询", CommonConst.LOGFIND, CommonConst.LOGTYPEBYADMIN);
		else
			saveLog("客户", "查询", CommonConst.LOGFIND, CommonConst.LOGTYPEBYUSER);
		return LIST;
	}
	public String update(){
		/*if(getCurrentUser()!=null && getCurrentUser().getToUpdate()!=null && (getCurrentUser().getToUpdate().equals("0")||getCurrentUser().getToUpdate()==null)){
			result = "对不起，您没有修改的权限，请联系管理员开通修改权限!";
			return list();
		}*/
		TdClient td = new TdClient();
		clientService.load(td, entity.getClientId());
		ObjectUtil.extend(td, entity);
		clientService.update(td);
		result = "修改成功!";
		if(getCurrentAdmin()!=null)
			saveLog("客户", result, CommonConst.LOGUPDATE, CommonConst.LOGTYPEBYADMIN);
		else
			saveLog("客户", result, CommonConst.LOGUPDATE, CommonConst.LOGTYPEBYUSER);
		return list();
	}
	public String del(){
		/*if(getCurrentUser()!=null && getCurrentUser().getToDelete()!=null && (getCurrentUser().getToDelete().equals("0")||getCurrentUser().getToDelete()==null)){
			result = "对不起，您没有删除的权限，请联系管理员开通删除权限!";
			return list();
		}*/
		clientService.load(entity, entity.getClientId());
		entity.setState("3");
		clientService.update(entity);
		result = "删除成功!";
		
		if(getCurrentAdmin()!=null)
			saveLog("客户", "查询", CommonConst.LOGDEL, CommonConst.LOGTYPEBYADMIN);
		else
			saveLog("客户", "查询", CommonConst.LOGDEL, CommonConst.LOGTYPEBYUSER);
		return list();
		
	}
	public String allDel() {
		/*if(getCurrentUser()!=null && getCurrentUser().getToDelete()!=null && (getCurrentUser().getToDelete().equals("0")||getCurrentUser().getToDelete()==null)){
			result = "对不起，您没有删除的权限，请联系管理员开通删除权限!";
			return list();
		}*/
		if(clientIds!=null&&clientIds.length!=0){
			String name = "";
			for(int uId:clientIds){
				TdClient td = (TdClient) baseService.findById(entityClass, uId);
				name +=(td.getName()+",");
				td.setState("3");
				baseService.update(td);
			}
			result = "删除成功!";
			if(getCurrentAdmin()!=null)
				saveLog("客户:"+name, result, CommonConst.LOGDEL, CommonConst.LOGTYPEBYADMIN);
			else
				saveLog("客户:"+name,result, CommonConst.LOGDEL, CommonConst.LOGTYPEBYUSER);
		}
		return list();
	}
	public String edit(){
		clientService.load(entity, entity.getClientId());
		return EDIT;
	}
	public String toEmail(){
		return "email";
	}
	public String mailForm(){
		List<TdEmailAccount> list = (baseService.findAll(TdEmailAccount.class));
		if(list.isEmpty()){
			result = "您的邮件服务器信息未配置!请先到(系统配置--email管理)配置!";
			return "email";
		}
		String[] m = emails.split(",");
		TdEmailAccount ta = list.get(0);
		for(String mm:m){
			if(StringUtil.isNotBlank(mm.trim()))
				result = clientService.sendEmail(ta.getSmtpName(), ta.getEmail(), ta.getAccount(), ta.getPassword(), mm, title, content);
		}
		if(getCurrentAdmin()!=null)
			saveLog("email", "发送email"+m+"message:"+result, CommonConst.LOGSAVE, CommonConst.LOGTYPEBYADMIN);
		else
			saveLog("email", "发送email"+m+"message:"+result, CommonConst.LOGSAVE, CommonConst.LOGTYPEBYUSER);
		return "email";
	}
	public String expExcel(){
		//第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("客户表一");
        //第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int)0);
        //第四步，创建单元格，并设置值表头  设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //创建一个居中格式
        
        HSSFCell cell = row.createCell((short)0);
        cell.setCellValue("姓名"); cell.setCellStyle(style);
        cell = row.createCell((short)1);
        cell.setCellValue("电话"); cell.setCellStyle(style);
        cell = row.createCell((short)2);
        cell.setCellValue("手机"); cell.setCellStyle(style);
        cell = row.createCell((short)3);
        cell.setCellValue("email"); cell.setCellStyle(style);
        cell = row.createCell((short)4);
        cell.setCellValue("添加时间"); cell.setCellStyle(style);
        cell = row.createCell((short)5);
        cell.setCellValue("备注"); cell.setCellStyle(style);
        cell = row.createCell((short)6);
        
        //第五步，写入实体数据 实际应用中这些数据从数据库得到，
        DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
        List list = clientService.findAllByCriteria(dc);

        for(int i=0;i<list.size();i++){
            row = sheet.createRow((int)i+1);
            TdClient tc = (TdClient) list.get(i);
            //第四步，创建单元格，并设置值
            row.createCell((short)0).setCellValue(tc.getName());
            row.createCell((short)1).setCellValue(tc.getPhone());
            row.createCell((short)2).setCellValue(tc.getCellphone());
            row.createCell((short)3).setCellValue(tc.getEmail());
            cell = row.createCell((short)4);
            cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(tc.getAddTime()));
            row.createCell((short)5).setCellValue(tc.getPdesc());
        }
        //第六步，将文件存到指定位置
        String path = getRequest().getRealPath("excel-temp");
        File dir = new File(path);
		if (!dir.exists())
			dir.mkdirs();
        try {
            FileOutputStream fout = new FileOutputStream(path+"/client.xls");
            wb.write(fout);
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        result = "http://localhost:8080/excel-temp/"+"client.xls";
		return JSON;
	}
	public String getSearchKey() {
		return searchKey;
	}
	public void setSearchKey(String searchKey) {
		this.searchKey = searchKey;
	}
	public String getEmails() {
		return emails;
	}
	public void setEmails(String emails) {
		this.emails = emails;
	}
	

}
